package org.esisar.controller.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.esisar.controller.utils.SessionHelper;
import org.esisar.dao.JDBCDAO;
import org.esisar.dao.UserStatementCreator;
import org.esisar.exceptions.IncorrectCredentialsException;
import org.esisar.exceptions.UserExistException;
import org.esisar.model.User;

public class UserUtils {

	private static JDBCDAO jdbcdao = new JDBCDAO();

	public static HttpServletRequest login(HttpServletRequest req) throws IOException, ServletException, SQLException, IncorrectCredentialsException{

		String login = req.getParameter("email");
		String password = req.getParameter("password");
		String admin = req.getParameter("admin");


		User user = (User) jdbcdao.find(new UserStatementCreator(), "email", login);

		if (user == null || !user.getPasswd().equals(password)){
			throw new IncorrectCredentialsException("Incorrect login or passwrord");
		}
		/*		if(!user.getEmail().equals("admin"))	{
			throw new IncorrectCredentialsException("You are not an admin");
		}
		 */			req.getSession().setAttribute("id", user.getIdClient());	//setting attribute to session
		 req.setAttribute("email", user.getEmail());
		 req.setAttribute("admin", admin);

		 return req;
	}

	
	public static HttpServletRequest register(HttpServletRequest req) throws ServletException, IOException, SQLException, UserExistException {
		String name = req.getParameter("name");
		String surname = req.getParameter("surname");
		String email = req.getParameter("email");
		String passwd = req.getParameter("passwd");
					User foundUser = (User) jdbcdao.find(new UserStatementCreator(), "email", email);
			if(foundUser != null){
				throw new UserExistException("Mail already used");
			}

			User user = new User(email, name, surname, passwd);
			jdbcdao.addToDB(new UserStatementCreator(), user);

			req.setAttribute("message", "Account created. You can log in");
			
			return req;
	}


	public static void logout(HttpServletRequest req) {
		SessionHelper.removeUserId(req);
		req.setAttribute("message", "Logout successful");
	}




}
